import json
import os

def convert_to_formatted_text(data):
    formatted_output = []
    
    for i, item in enumerate(data, start=1):
        # 题目标题编号及题型标识
        title = f"{i}. {item['题干']}【单选题】"
        formatted_output.append(title)
        
        # 添加选项
        for option, text in item.get("选项", {}).items():
            if option == item['答案']:
                formatted_output.append(f"{option}: {text}（正确答案）")
            else:
                formatted_output.append(f"{option}: {text}")
        
        # 添加AI解析
        formatted_output.append(f"答案解析：{item['AI解析']}")
        
        # 添加标签
        formatted_output.append(f"标签：{item['知识点']}")
        
        # 添加空行作为分隔符
        formatted_output.append("")

    return "\n".join(formatted_output)

def process_json_files_in_directory(input_directory, output_directory):
    # 确保输出文件夹存在
    os.makedirs(output_directory, exist_ok=True)

    for root, _, files in os.walk(input_directory):
        for file_name in files:
            if file_name.endswith(".json"):
                json_file_path = os.path.join(root, file_name)
                txt_file_name = os.path.splitext(file_name)[0] + ".txt"
                txt_file_path = os.path.join(output_directory, txt_file_name)
                
                # 读取 JSON 文件
                with open(json_file_path, "r", encoding="utf-8") as json_file:
                    data = json.load(json_file)

                # 转换格式
                formatted_text = convert_to_formatted_text(data)

                # 保存为 TXT 文件
                with open(txt_file_path, "w", encoding="utf-8") as txt_file:
                    txt_file.write(formatted_text)

                print(f"已将 {json_file_path} 转换为 {txt_file_path}")

# 指定输入文件夹路径
input_directory_path = r"dataset_question bank\question_json"
# 指定输出文件夹路径
output_directory_path = r"dataset_question bank\question_txt"
process_json_files_in_directory(input_directory_path, output_directory_path)
